<template>
	<view>
		
		<!-- 小程序顶部样式 -->
		<cu-custom bgColor="bg-blue" :isBack="true">
			<block slot="content">登陆</block>
		</cu-custom>
		
		<image src="/static/home-bg.png" mode="scaleToFill" style="height: 300rpx;width: 100%;position: absolute;"></image>
		<view class="flex justify-center align-center">
			<image src="/static/indexLogo.png" mode="scaleToFill"
			style="height: 60rpx;width: 30%;position: absolute;margin-top: 150rpx;"></image>
		</view>
		
		<view class="flex justify-center flex-direction align-center" style="margin-top: 400rpx;">
			<button style="margin-top: 20upx;width: 90%;background-color: #0081ff;" 
			type="primary" class="primary" 
			open-type="getUserInfo" @getuserinfo="onGotUserInfo" >微信授权登陆</button>
		</view>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				reqBody:{
					code: '',
					encryptedData: '',
					iv: '',
					key: this.$util.getKey()
				}
			}
		},
		onLoad() {
			let that = this
			uni.login({
				success(loginRes) {
					that.reqBody.code = loginRes.code
				}, 
			})
		},
		methods: {
			onGotUserInfo(val){
				if(val && val.target && val.target.errMsg && val.target.errMsg.toString().indexOf('ok') == -1){
					// 授权失败
					uni.showModal({
						title: '请授权',
						content: '授权失败可能会无法使用小程序！',
						success: function (res) {
							if (res.confirm) {
								console.log('用户点击确定');
							} else if (res.cancel) {
								console.log('用户点击取消');
							}
						}
					});
				}else{
					this.getUserInfoApi(val)
				}
			},
			getUserInfoApi(val){
				if(val && val.detail){
					this.reqBody.encryptedData = val.detail.encryptedData
					this.reqBody.iv = val.detail.iv
					// 获取用户信息
					this.$api.login(this.reqBody).then((res)=>{
						uni.setStorageSync('uid', res.data.data.uid)
						this.$store.dispatch('dispatchUserInfo')
						uni.navigateBack({
							delta: 1
						})
					}).catch((err)=>{
						console.log('request fail', err);
					})
				}
			},
		}
	}
</script>

<style>

</style>
